package com.ningjingjing.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningjingjing.DBUtil;
import com.ningjingjing.model.Album;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/album-list.json")
public class AlbumListApi extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 问题：每次返回所有的专辑，当专辑数量变多时，这种实现非常不合适
        List<Album> albumList = new ArrayList<>();
        Object result;

        // 从 MySQL 中拿到所有的专辑列表
        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT aid, name, cover, count FROM album ORDER BY aid DESC";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                try (ResultSet rs = s.executeQuery()) {
                    while (rs.next()) {
                        Album album = new Album();
                        album.aid = rs.getInt("aid");
                        album.name = rs.getString("name");
                        album.cover = rs.getString("cover");
                        album.count = rs.getInt("count");

                        albumList.add(album);
                    }
                }
            }

            result = new Object() {
                public boolean success = true;
                public Object data = albumList;
            };
        } catch (SQLException exc) {
            // 1. 打印异常栈，便于找到出错原因
            exc.printStackTrace();
            // 2. 把异常中的消息作为错误原因写到 API 中
            result = new Object() {
                public boolean success = false;
                public String reason = exc.getMessage();
            };
        }

        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}